import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmfmap_example/http/http.dart';
import 'package:flutter_bmfmap_example/models/ordermodel.dart';
// import 'package:flutter_application_1/test/tool.dart';
import 'package:fluttertoast/fluttertoast.dart';
// import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:image_picker/image_picker.dart';

class EvalutePage extends StatefulWidget {
  EvalutePage({Key key, this.orderItem}) : super(key: key);

  OrderItem orderItem;

  @override
  _EvalutePageState createState() => _EvalutePageState();
}

class _EvalutePageState extends State<EvalutePage> {
  //上传图片用

  List<Widget> _img = [];
  List<String> _imgurl = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _img.add(
      DottedBorder(
        borderType: BorderType.RRect,
        color: Colors.red,
        radius: Radius.circular(10),
        child: InkWell(
          child: Container(
            height: 88,
            width: 88,
            decoration: BoxDecoration(
                // border: Border()

                ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [Icon(Icons.camera_alt), Text("选择商品图片")],
            ),
          ),
          onTap: () {
            // this._openGallerySystem();
            _pickImage();
          },
        ),
      ),
    );
  }

  // 上传
  upLoadEvaluate(dynamic item, myIntro) async {
    print('提交评价');
    print(item["commodityId"]);
    print(widget.orderItem.id);
    print(_imgurl);
    var isOk = false;
    var params = {
      "commodityId": item["commodityId"],
      "orderFormId": widget.orderItem.id,
      "info": myIntro,
      "imgurl1":_imgurl.length>=1? _imgurl[0]:null,
      "imgurl2":_imgurl.length>=2? _imgurl[1]:null,
      "imgurl3":_imgurl.length>=3? _imgurl[2]:null,
      "imgurl4":_imgurl.length>=4? _imgurl[3]:null,
    };
    String url = "/evaluate";
    var response = await Http.post(url, params: params);
    print(response);
    isOk = response;
    if (isOk != false) {
      Fluttertoast.showToast(
          msg: "操作成功",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black45,
          textColor: Colors.white,
          fontSize: 16.0);
    } else {
      Fluttertoast.showToast(
          msg: "操作失败",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black45,
          textColor: Colors.white,
          fontSize: 16.0);
    }
  }

  Widget build(BuildContext context) {
    final myController = TextEditingController();
    var evaText = myController.text;
    myController.addListener(() {
      print(myController.text);
      evaText = myController.text;
    });

    return Scaffold(
      appBar: AppBar(
        title: Text('商品评价'),
        centerTitle: true,
      ),
      body: Container(
        child: ListView(children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Container(
              // height: 420,
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Colors.grey[200],
              ),
              child: Column(
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        child: Image.network(
                          widget.orderItem.orderitems[0]["imgurl1"],
                          width: 56,
                          height: 56,
                        ),
                      ),
                      SizedBox(width: 12),
                      Expanded(
                        child: Container(
                            child: Text(
                          widget.orderItem.orderitems[0]["intro"],
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 13),
                        )),
                      )
                    ],
                  ),
                  Container(
                    child: TextField(
                      controller: myController,
                      maxLines: 10,
                      maxLength: 200,
                      style: TextStyle(fontSize: 13, color: Colors.grey[800]),
                      decoration: InputDecoration(
                        hintText: '宝贝收到了吧，感觉不错的话，就和大家分享一下自己的心得吧，谢谢您！',
                        hintStyle:
                            TextStyle(fontSize: 13, color: Colors.grey[600]),
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  Container(
                    height: 88,
                    width: 400,
                    child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: _img.length,
                        itemBuilder: (BuildContext ctxt, int index) {
                          return _img[index];
                        }),
                  ),
                  Divider(),
                  InkWell(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(12, 6, 12, 6),
                      decoration: BoxDecoration(
                          border:
                              Border.all(color: Colors.grey[400], width: 0.5),
                          borderRadius: BorderRadius.circular(20),
                          gradient: LinearGradient(
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                              // stops: [0.0,1.0],
                              colors: [Colors.pink[200], Colors.orange])),
                      child: Text(
                        '提交评论',
                        style: TextStyle(color: Colors.white, fontSize: 13),
                      ),
                    ),
                    onTap: () async {
                      print('$evaText');
                      upLoadEvaluate(widget.orderItem.orderitems[0], evaText);
                    },
                  )
                ],
              ),
            ),
          ),
        ]),
      ),
    );
  }

  _pickImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);

    await _upLoadImage(image).then((value) {
      // _img.insert(0, _ImageView(value));
      _img.add(_ImageView(value));
      _imgurl.add(value);
      print('添加成功');
      setState(() {});
    });
  }

  Future<String> _upLoadImage(File image) async {
    String path = image.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData = new FormData.fromMap(
        {"imageFile": await MultipartFile.fromFile(image.path)});

    String url = "/upload/image";
    var response = await Http.post(url, data: formData);
    print(response);

    if (response != null) {
      print(response);
      // Fluttertoast.showToast(
      //     msg: "图片上传成功", gravity: ToastGravity.CENTER, textColor: Colors.grey);
      // UserHepler.getInstance.setportraiturl(respone.data);
      // _updateportrait(respone.data);
    } else
      print("wrong");
    return response;
  }

  _ImageView(String url) {
    return Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadiusDirectional.circular(20)),
      clipBehavior: Clip.antiAlias,
      child: Image.network(url),
    );
  }
}
